package stream;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 *
 * sorted，中间操作。有两种排序：
 *
 * sorted()：自然排序，流中元素需实现Comparable接口
 * sorted(Comparator com)：Comparator排序器自定义排序
 *
 * @author Hongliang Zhu
 * @create 2021-08-01 16:28
 */
public class Demo11 {
    public static void main(String[] args) {

        //案例：将员工按工资由高到低（工资一样则按年龄由大到小）排序


        List<Person> personList = new ArrayList<Person>();

        personList.add(new Person("Sherry", 9000, 24, "female", "New York"));
        personList.add(new Person("Tom", 8900, 22, "male", "Washington"));
        personList.add(new Person("Jack", 9000, 25, "male", "Washington"));
        personList.add(new Person("Lily", 8800, 26, "male", "New York"));



        // 按工资升序排序（自然排序）
        List<String> collect = personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName).collect(Collectors.toList());
        System.out.println(collect);
        // 按工资倒序排序
        List<String> newList2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed())
                .map(Person::getName).collect(Collectors.toList());

        List<Person> collect1 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed()).collect(Collectors.toList());
        // 先按工资再按年龄自然排序（从小到大）
        List<Person> collect2 = personList.stream().sorted((p1, p2) -> {
            if (p1.getSalary() != p2.getSalary()) {
                return p1.getSalary() - p2.getSalary();
            } else {
                return p1.getAge() - p2.getAge();
            }
        }).collect(Collectors.toList());

        System.out.println(collect2);


    }
}
